package a66weding.com.jiehuntong.common.utils.uploadimage;

import android.util.Log;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;

import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.beans.UpLoadImage;

/**
 * Created by admin on 2016/7/26.
 */
public class UpLoadUtil  {
    private String baseurl ;
    private File file;
    private ResultCallBack resultCallBack;
    private UpLoadImage upLoadImage;

    public UpLoadUtil(String url,File file,ResultCallBack resultCallBack){
        this.baseurl = url;
        this.file = file;
        this.resultCallBack = resultCallBack;

    }

    public  String uploadFile(File file,String RequestURL) {
        String result="";
        String BOUNDARY = UUID.randomUUID().toString();
        //边界标识 随机生成
        String PREFIX = "--" , LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; //内容类型
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10*100000); conn.setConnectTimeout(10*100000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST"); //请求方式
            conn.setRequestProperty("Charset", "utf-8");
            //设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            if(file!=null) {
                /** * 当文件不为空，把文件包装并且上传 */
                OutputStream outputSteam=conn.getOutputStream();
                DataOutputStream dos = new DataOutputStream(outputSteam);
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END);
                sb.append("Content-Type: application/octet-stream; charset=utf-8"+LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while((len=is.read(bytes))!=-1)
                {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功
                 * 当响应成功，获取响应的流
                 */
                int res = conn.getResponseCode();
                if(res==200)
                {
                    // 读取返回数据
                    StringBuffer strBuf = new StringBuffer();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        strBuf.append(line).append("\n");
                    }
                    result = strBuf.toString();
                    reader.close();
                    Gson mgson = new Gson();
                    UpLoadImage upLoadImage = mgson.fromJson(result,UpLoadImage.class);
                    if(resultCallBack!=null) {
                        resultCallBack.getResult(upLoadImage);

                    }
                    return result;
                }else{
                    UpLoadImage upLoadImage = new UpLoadImage();
                    upLoadImage.setResCode("0004");
                    if(resultCallBack!=null) {
                        resultCallBack.getResult(upLoadImage);
                    }
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            UpLoadImage upLoadImage = new UpLoadImage();
            upLoadImage.setResCode("0004");
            if(resultCallBack!=null) {
                resultCallBack.getResult(upLoadImage);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
            UpLoadImage upLoadImage = new UpLoadImage();
            upLoadImage.setResCode("0004");
            if(resultCallBack!=null) {
                resultCallBack.getResult(upLoadImage);
            }
        }
        return result;
    }


    public void startUploadImage(){
        uploadfile(file);
    }

    private void uploadfile(final File saveFile) {
        //图片上传地址
        String phone = DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_MobilePhone();
        String id = ""+DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
        final String url = baseurl+"&mobileStr="+phone+"&bookId=" + id;
        new Thread() {
            @Override
            public void run() {
                String result = uploadFile(saveFile, url);
                try {
                    Gson mgson = new Gson();
                    UpLoadImage upLoadImage = mgson.fromJson(result,UpLoadImage.class);
                    Log.e("解析的数据是",""+upLoadImage);
                    resultCallBack.getResult(upLoadImage);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    public interface  ResultCallBack{
        public void  getResult( UpLoadImage upLoadImage);
    }
}
